
from undirected_graph_util import *


__all__ = ['build_from_relation_string', 'build_classic_undirected_graph']

def build_from_relation_string(relation_str):
    nodes = {}      # {label : UnDirectedGraphNode}

    def get_node(label):
        if label not in nodes:
            nodes[label] = UnDirectedGraphNode(label)
        return nodes[label]

    def add_nei(node, nei):
        if nei not in node.neighbors:
            node.neighbors.append(nei)

    relations = relation_str.split('#')
    for rel in relations:
        labels = rel.split(',')

        src_node = get_node(labels[0])

        for label in labels[1:]:
            dst_node = get_node(label)
            add_nei(src_node, dst_node)
            add_nei(dst_node, src_node)
            # src_node.neighbors.append(dst_node)

    graph = list(nodes.values())
    return graph

def build_classic_undirected_graph():
    # relation_str = "a,b#b,c,e,f#c,d,g#d,c,h#e,a,f#f,g#g,f#h,d,g"
    # relation_str = "1,2#2,3#3,1"     # 1指向2,3, 2指向3
    # relation_str = "1,2#3,1"
    # relation_str = "1,2#2,3#3,4#4,5#5,1"
    # relation_str = "1,2#2,3#3,4#4,5"
    relation_str = "1,2,3#2,4#3,4#4,5,6#5,2,6"
    # relation_str = "1,2,3#2,4#3,4#4,5,6"
    return build_from_relation_string(relation_str)

# ===================  =====================
def test_build_from_str():
    # relation_str = "1,2#2,3"     # 1指向2,3, 2指向3
    # graph = build_from_relation_string(relation_str)
    graph = build_classic_undirected_graph()

    for node in graph:
        print(node)
        for nei in node.neighbors:
            print("----> %s" % nei)
        print()

def main():
    print("start main")
    test_build_from_str()

if __name__ == "__main__":
    main()

